package com.ruoyi.plasma.controller;

import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.tongji.run.manager.ManagerFactory;
import com.ruoyi.tongji.run.智能客服回访名单;
import com.ruoyi.tongji.utils.DateUtil;
import org.apache.commons.io.IOUtils;
import org.beetl.sql.core.SQLManager;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.plasma.domain.PlasmaFollowUp;
import com.ruoyi.plasma.service.IPlasmaFollowUpService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 回访管理Controller
 * 
 * @author ruoyi
 * @date 2024-08-15
 */
@RestController
@RequestMapping("/plasma/followup")
public class PlasmaFollowUpController extends BaseController
{
    @Autowired
    private IPlasmaFollowUpService plasmaFollowUpService;

    /**
     * 查询回访管理列表
     */
    @PreAuthorize("@ss.hasPermi('plasma:followup:list')")
    @GetMapping("/list")
    public TableDataInfo list(PlasmaFollowUp plasmaFollowUp)
    {
        startPage();
        List<PlasmaFollowUp> list = plasmaFollowUpService.selectPlasmaFollowUpList(plasmaFollowUp);
        return getDataTable(list);
    }

    /**
     * 导出回访管理列表
     */
    @PreAuthorize("@ss.hasPermi('plasma:followup:export')")
    @Log(title = "回访管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PlasmaFollowUp plasmaFollowUp)
    {
        List<PlasmaFollowUp> list = plasmaFollowUpService.selectPlasmaFollowUpList(plasmaFollowUp);
        ExcelUtil<PlasmaFollowUp> util = new ExcelUtil<PlasmaFollowUp>(PlasmaFollowUp.class);
        util.exportExcel(response, list, "回访管理数据");
    }

    /**
     * 生成回访名单
     * @param response
     */
    @PreAuthorize("@ss.hasPermi('plasma:followup:export')")
    @Log(title = "回访管理", businessType = BusinessType.IMPORT)
    @GetMapping("/create")
    public void create(HttpServletResponse response) throws IOException {
        String root = "E:\\文档\\2024\\回访记录\\智能客服回访\\";//RuoYiConfig.getFollowupfile();
        //List list_19 = new ArrayList<>();
        //HashMap obj = new HashMap();obj.put("donorno","3701002169");obj.put("donorname","孙哲");obj.put("phone","18663765675");
        //list_19.add(obj);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        System.out.println("create");

        List list_14 = 智能客服回访名单.create14tianCannotRegisterList();//查询日期后一天不能来的浆员
        List list_19 = 智能客服回访名单.createFollowUpListExclude24Times(-19,-19);
        List list_30 = 智能客服回访名单.createFollowUpListExclude24Times(-30,-30);
        List list_60 = 智能客服回访名单.createFollowUpListUnexclude24Times(-60,-60);
        List list_90 = 智能客服回访名单.createFollowUpListUnexclude24Times(-90,-90);
        List list_180 = 智能客服回访名单.createFollowUpListUnexclude24Times(-180,-180);
        List list_270 = 智能客服回访名单.createFollowUpListUnexclude24Times(-270,-270);
        List list_365 = 智能客服回访名单.createFollowUpListUnexclude24Times(-365,-365);

        HashMap allFollowUpData = new HashMap();
        List allFollowUpList = new ArrayList();

        allFollowUpList.addAll(list_19);
        allFollowUpList.addAll(list_30);
        allFollowUpList.addAll(list_60);
        allFollowUpList.addAll(list_90);
        //allFollowUpList.addAll(list_180);//招募科人工回访的，不放在智能回访数量中，需要智能回访时再取消注释
        allFollowUpList.addAll(list_270);
        allFollowUpList.addAll(list_365);

        allFollowUpData.put("donorList",allFollowUpList);

        FileUtils.putZip(zip,this.saveFollowUp(list_14, "14天（24次提醒）", root));
        FileUtils.putZip(zip,this.saveFollowUp(list_19, "19天", root));
        FileUtils.putZip(zip,this.saveFollowUp(list_30, "30天", root));
        FileUtils.putZip(zip,this.saveFollowUp(list_60, "60天", root));
        FileUtils.putZip(zip,this.saveFollowUp(list_90, "90天", root));
        FileUtils.putZip(zip,this.saveFollowUp(list_180, "180天（宣传招募科回访）", root));
        FileUtils.putZip(zip,this.saveFollowUp(list_270, "270天", root));
        FileUtils.putZip(zip,this.saveFollowUp(list_365, "365天", root));

        String ymd = DateUtil.format(new Date(), "yyyy年M月d日");
        File rootFile = new File(root + "//" + ymd);
        rootFile.mkdirs();
        File f = ManagerFactory.createExcel(root,"excelTemplates/智能客服回访/回访模版.xlsx",ymd + "//总(" + allFollowUpList.size() + ")-" + ymd + ".xlsx",allFollowUpData);

        FileUtils.putZip(zip,f);
        IOUtils.closeQuietly(zip);

        byte[] data = outputStream.toByteArray();
        if (response != null) {
            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            IOUtils.write(data, response.getOutputStream());
        }
    }

    private File saveFollowUp(List followupList, String type, String root) {
        for (Iterator<HashMap> iterator = followupList.iterator(); iterator.hasNext(); ) {
            HashMap next =  iterator.next();
            String donorNo = (String)next.get("donorno");
            String donorName = (String)next.get("donorname");
            String followUpDate = DateUtil.format(new Date(),"yyyy-MM-dd");
            Date insertTime = new Date();


            PlasmaFollowUp followUp = new PlasmaFollowUp();
            followUp.setDonorNo(donorNo);
            followUp.setDonorName(donorName);
            followUp.setFollowUpDate(followUpDate);
            followUp.setType(type);

            List l = plasmaFollowUpService.selectPlasmaFollowUpList(followUp);

            if (l.size() == 0) {
                followUp.setInsertTime(insertTime);
                plasmaFollowUpService.insertPlasmaFollowUp(followUp);
            }
        }

        if (followupList.size() > 0){
            Map data = new HashMap();
            data.put("donorList",followupList);
            String ymd = DateUtil.format(new Date(), "yyyy年M月d日");
            File rootFile = new File(root + "//" + ymd);
            rootFile.mkdirs();
            File f = ManagerFactory.createExcel(root,
                    "excelTemplates/智能客服回访/回访模版.xlsx",
                    ymd + "//"+ type +"（" + followupList.size() + "）.xlsx",data);

            return f;
        } else {
            return null;
        }

    }



    /**
     * 获取回访管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('plasma:followup:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(plasmaFollowUpService.selectPlasmaFollowUpById(id));
    }

    /**
     * 新增回访管理
     */
    @PreAuthorize("@ss.hasPermi('plasma:followup:add')")
    @Log(title = "回访管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PlasmaFollowUp plasmaFollowUp)
    {
        return toAjax(plasmaFollowUpService.insertPlasmaFollowUp(plasmaFollowUp));
    }

    /**
     * 修改回访管理
     */
    @PreAuthorize("@ss.hasPermi('plasma:followup:edit')")
    @Log(title = "回访管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PlasmaFollowUp plasmaFollowUp)
    {
        return toAjax(plasmaFollowUpService.updatePlasmaFollowUp(plasmaFollowUp));
    }

    /**
     * 删除回访管理
     */
    @PreAuthorize("@ss.hasPermi('plasma:followup:remove')")
    @Log(title = "回访管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(plasmaFollowUpService.deletePlasmaFollowUpByIds(ids));
    }
}
